package com.quzi.kettle.activitise.main;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.httprequest.AsyncBean;
import com.example.httprequest.AsyncHttpUtilClient;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.loopj.android.http.Base64;
import com.loopj.android.http.RequestParams;
import com.quzi.kettle.GlobalConfig;
import com.quzi.kettle.MyApplication;
import com.quzi.kettle.R;
import com.quzi.kettle.activitise.BaseActivity;
import com.quzi.kettle.activitise.added.Modes2Activity;
import com.quzi.kettle.activitise.added.WaterDateUtil;
import com.quzi.kettle.api.response.IconResponse;
import com.quzi.kettle.api.response.UpdateInfoResponse;
import com.quzi.kettle.bean.ChannelObject;
import com.quzi.kettle.bean.ModeItem;
import com.quzi.kettle.bean.http.IconString;
import com.quzi.kettle.datapiece.FactoryDataBody;
import com.quzi.kettle.datapiece.status.DeviceStatus;
import com.quzi.kettle.push.MQTTService;
import com.quzi.kettle.push.PushCallback;
import com.quzi.kettle.push.Thermometer;
import com.quzi.kettle.utils.AlertUtil;
import com.quzi.kettle.utils.BoliModeUtil;
import com.quzi.kettle.utils.ByteUtils;
import com.quzi.kettle.utils.DateUtils;
import com.quzi.kettle.utils.ImageUtils;
import com.quzi.kettle.utils.MSharePerference;
import com.quzi.kettle.utils.NetworkStatusUtil;
import com.quzi.kettle.view.CustomDialogInterface;
import com.quzi.kettle.view.MNumberPicker;
import com.quzi.kettle.view.MNumberReceive;
import com.quzi.kettle.view.TitleBarHandler;
import com.quzi.kettle.view.TitleBarView;

public class MainActivityTest extends BaseActivity implements MNumberReceive {

	private final int UPDATE_VIEW = 1;
	public final int DISNUMBER = 0;
	public final int UPDATE_BOILING_VIEW = 2;
	public final int ONLINE = 3;
	public final int OFFLINE = 4;
	public final int QUERY = 5;
	protected static final int TEST_AUTO_ADD = 6;
	protected static final int menuclose = 8;
	private boolean isDialog = false;

	public static final String SERVICE_CLASSNAME = "com.quzi.kettle.push.MQTTService";
	private SlidingMenu menu;
	private LinearLayout menu_all_device, menu_share, menu_upgread;

	private TitleBarView titleView;

	private LinearLayout appoint_layout, boil_layout, linear_main_controlline;
	private RelativeLayout rela_total;
	private PopupWindow pw;
	private boolean initPop = false;

	private View CtlMenu;
	private TextView Temperature, /* tv_main_templabel, */BoilStatus, temp_unit;
	private TextView button1;

	private TextView Watertank, modeName;

	public static boolean needSaveMode = false;
	public static boolean isStart = false;
	private int nowWaterLevel = 0;
	private int nowTempLevel = 0;
	private int cleanCLtime = 0;// 除氯时间
	private int keepWarm_temperature = 80;// 保温温度
	private int setTemperature = 0;

	private MNumberPicker mNumberPicker;
	private LinearLayout main_control;
	private RelativeLayout boilinglayout;
	private Button stopBoil;

	private boolean baowening = false;

	private static boolean isShown = false;// 记录侧边栏是否出现
	byte zeroByte;
	private Animation enter_righttoleft;
	private TextView tv1, tv2, tv3;
	private ImageView im1, im2, im3;

	// 开启服务
	private void startBlackIceService() {
		if (NetworkStatusUtil.isConnected(getApplicationContext())) {
			if (!TEST_MODE) {
				final Intent intent = new Intent(this, MQTTService.class);
				startService(intent);
				if (getTopic().isEmpty()) {
					UIHandler.obtainMessage(TOASTMSG, "请先添加您的设备")
							.sendToTarget();
				}
			}
			Log.d("mmqtt", "开启服务   topic = " + getTopic());
		} else {
			UIHandler.obtainMessage(TOASTMSG, "请检查网络").sendToTarget();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	// 关闭服务
	private void stopBlackIceService() {
		if (NetworkStatusUtil.isConnected(getApplicationContext())) {
			final Intent intent = new Intent(this, MQTTService.class);
			stopService(intent);
		} else {
			UIHandler.obtainMessage(TOASTMSG, "请检查网络").sendToTarget();
		}
	}

	// 服务运行状态
	private boolean serviceIsRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		for (ActivityManager.RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (SERVICE_CLASSNAME.equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	Handler handler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			switch (msg.what) {
			case menuclose:
				isShown = false;
				menu.toggle();
				break;
			case DISNUMBER:
				if (mNumberPicker.isShowing()) {
					mNumberPicker.dismiss();
				}
				break;
			case UPDATE_VIEW:
				updateView();
				break;
			case UPDATE_BOILING_VIEW:
				updateUI(status,
						MSharePerference.getInstance(getApplicationContext())
								.get(GlobalConfig.MODE));
				break;
			case ONLINE:

				break;
			case OFFLINE:
				Toast.makeText(getApplicationContext(), "设备不在线",
						Toast.LENGTH_SHORT).show();
				break;
			case QUERY:
				if (!hasQuery) {
					hasQuery = true;
					sendQueryCommand();
				}
				break;
			case TEST_AUTO_ADD:
				status.setTemperature++;
				if (status.setTemperature < targetTemperature) {
					handler.sendEmptyMessageDelayed(TEST_AUTO_ADD, 1000);
				} else {
					status.runNingStatus = 0;
				}
				updateBoilingStatus();
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main_test);

		// tv_main_templabel = (TextView) findViewById(R.id.tv_main_templabel);
		Temperature = (TextView) findViewById(R.id.temperature);
		temp_unit = (TextView) findViewById(R.id.unit);
		Temperature.setIncludeFontPadding(false);
		Temperature.setOnClickListener(this);
		BoilStatus = (TextView) findViewById(R.id.boiling);
		BoilStatus.setVisibility(View.GONE);
		boilinglayout = (RelativeLayout) findViewById(R.id.boilinglayout);
		boilinglayout.setVisibility(View.GONE);
		stopBoil = (Button) findViewById(R.id.boilingbtn);
		stopBoil.setOnClickListener(this);
		Watertank = (TextView) findViewById(R.id.watertank);
		main_control = (LinearLayout) findViewById(R.id.main_control);
		modeName = (TextView) findViewById(R.id.maintext);
		main_control.setOnClickListener(this);
		button1 = (TextView) findViewById(R.id.button1);
		findViewById(R.id.button1).setOnClickListener(this);
		findViewById(R.id.currmode).setOnClickListener(this);
		modeName.setOnClickListener(this);

		initMenu();
		initTitleBar();
		initCtlMenu();
		saveCurrentMode(true);
		updateCurrentData();
		findViewById(R.id.relative).setOnClickListener(this);
		appoint_layout = (LinearLayout) findViewById(R.id.appoint_layout);
		appoint_layout.setOnClickListener(this);
		boil_layout = (LinearLayout) findViewById(R.id.boil_layout);
		boil_layout.setOnClickListener(this);
		rela_total = (RelativeLayout) findViewById(R.id.relative);
		// 启动和预约中间的那条线
		linear_main_controlline = (LinearLayout) findViewById(R.id.linear_main_controlline);

		status.setTemperature = 80;
		status.beeWarning = 1;
		status.get_rid_cl_work = 1;// 煮沸
		status.setFixedTemperatureTime = (byte) 120;// 保温时间

		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		GlobalConfig.clientId = "A-" + info.getMacAddress();

		initDemoData();
		if (currDevice.getMain_mac().equals("aabbccddeeff")) {
			// 虚拟水壶
			TEST_MODE = true;
		} else {
			TEST_MODE = false;
			// sendQueryCommand();
		}
		setTopic(deviceList.get(0).getMain_mac());
		GlobalConfig.topic = deviceList.get(0).getMain_mac();
		// /startService(new Intent(AlarmService.ACTION));

	}

	private void initDemoData() {
		// setTopic("c893464118a5");
		MSharePerference.getInstance(getApplicationContext()).update(
				GlobalConfig.TargetTemp, "80");
	}

	/**
	 * 更新煮水状态和水状态
	 */
	private void updateView() {
		updateBoilingStatus();
		updateWaterTank();
	}

	private void updateWaterTank() {

	}

	/**
	 * 更新煮水状态
	 */
	private void updateBoilingStatus() {
		if (isDialog) {
			return;
		}
		Log.d("mylog", "updateBoilingStatus  = " + status.switchStatus
				+ "     " + status.setTemperature);
		if (status.switchStatus == 0x01) {
			// 正在煮水
			updateTemperature(status.setTemperature + "");
			Log.d("datadev", "runNingStatus = " + status.runNingStatus);

			boilinglayout.setVisibility(View.VISIBLE);
			BoilStatus.setVisibility(View.VISIBLE);
			main_control.setVisibility(View.GONE);
			linear_main_controlline.setVisibility(View.GONE);

			if (status.appointed_timer_on == 1
					&& (status.appointed_timer_on_aboso_hour != 0 || status.appointed_timer_on_aboso_min != 0)) {
				BoilStatus.setText("预约中");
				BoilStatus
						.setTextColor(getResources().getColor(R.color.orange));
			} else {

				if (status.runNingStatus == 0x01) {
					BoilStatus.setText("加热中");
					BoilStatus.setTextColor(getResources().getColor(
							R.color.orange));
				} else {
					BoilStatus.setText("保温中");
					BoilStatus.setTextColor(getResources().getColor(
							R.color.white));
				}
			}
			Temperature.setTextColor(getResources().getColor(R.color.orange));
			temp_unit.setTextColor(getResources().getColor(R.color.orange));
			// tv_main_templabel.setTextColor(getResources().getColor(
			// R.color.orange));

		} else {
			// // 煮水结束
			// if (needSaveMode && isStart) {
			// Log.v("save", "inthe need save" + "-----煮水结束--->");
			// saveNewMode();
			// }
			boilinglayout.setVisibility(View.GONE);
			BoilStatus.setVisibility(View.GONE);
			main_control.setVisibility(View.VISIBLE);
			linear_main_controlline.setVisibility(View.VISIBLE);

			setVisibleWhenBolling(false);
			updateTemperature(MSharePerference.getInstance(
					getApplicationContext()).get(GlobalConfig.TargetTemp));
			Temperature.setTextColor(getResources().getColor(R.color.white));
			// tv_main_templabel.setTextColor(getResources().getColor(
			// R.color.white));
			temp_unit.setTextColor(getResources().getColor(R.color.white));

			boolean isProper = false;
			Log.v("save", " status.runNingStatus" + "-------->"
					+ status.runNingStatus);
			Log.v("save", "status.switchStatus" + "-------->"
					+ status.switchStatus);
			Log.v("save", "status.test1" + "-------->" + status.test1);
			if ((0 == status.runNingStatus) && 0 == status.switchStatus
					&& 0 == status.test1) {
				isProper = true;
				Log.v("save", "isproper" + "-------->" + isProper);
				Log.v("save",
						"zeroByte" + "-------->"
								+ ByteUtils.printHexString(zeroByte));

				Log.v("save", "needSaveMode" + "-------->" + needSaveMode);
				Log.v("save", "zeroByte == 0x91" + "-------->"
						+ (zeroByte == 0x91));
				Log.v("save", "zeroByte.equal 91" + "-------->"
						+ ByteUtils.getHexString(zeroByte).equals("91"));
				Log.v("save", "boilinglayout.getVisibility()" + "-------->"
						+ (boilinglayout.getVisibility() == View.GONE));
				if (isProper /* && ByteUtils.getHexString(zeroByte).equals("91") */
						&& boilinglayout.getVisibility() == View.GONE) {
					Log.v("save", "into 3 con" + "-------->");
					// [self postLocalNotificatio n];

					// [self AskToSaveMode];
					if (needSaveMode) {
						Log.v("save", "in the need save" + "-------->");
						saveNewMode();
					}
				} else {
					Log.v("save", "i can't get the ifneedsavemode");
				}
			}

		}

		// 煮水完成提示并保存模式

	}

	/**
	 * 更新煮水模式名字
	 * 
	 * @param name
	 */
	private void updateModeName(String name) {
		if (name.length() >= 10) {
			modeName.setTextSize(13);
		} else if (name.length() >= 8) {
			modeName.setTextSize(16);
		} else if (name.length() > 6) {
			modeName.setTextSize(20);
		} else {
			modeName.setTextSize(24);
		}
		modeName.setText(name);
		MSharePerference.getInstance(getApplicationContext()).update(
				GlobalConfig.MODE, name);
	}

	ModeItem currModeItem;

	/**
	 * 更新煮水模式
	 */
	private void updateModeName() {
		String modeNameStr = MSharePerference.getInstance(
				getApplicationContext()).get(GlobalConfig.MODE);
		if (needSaveMode) {
			modeNameStr = "自定义";
		}
		if (MSharePerference.getInstance(getApplicationContext()).get(
				GlobalConfig.MODE) == ""
				|| MSharePerference.getInstance(getApplicationContext()).get(
						GlobalConfig.MODE) == null) {
			updateModeName("茉莉花茶");
		} else {
			updateModeName(modeNameStr);
			List<ModeItem> modeLists = getModeList();
			for (int i = 0; i < modeLists.size(); i++) {
				if (modeName.equals(modeLists.get(i).getModeTitle())) {
					currModeItem = modeLists.get(i);
					break;
				}
			}
			if (currModeItem == null) {
				if (modeNameStr.equals("茉莉花茶")) {

				} else if (modeNameStr.equals("玫瑰花茶")) {

				} else if (modeNameStr.equals("经典绿茶")) {

				} else if (modeNameStr.equals("经典红茶")) {

				} else if (modeNameStr.equals("婴儿奶粉")) {

				} else if (modeNameStr.equals("咖啡饮品")) {

				}
			}
		}
		updateModeItem(modeNameStr);
	}

	/**
	 * 根据当前模式设置baseactivity中Devicestatus
	 * 
	 * @param modeNameStr
	 */
	private void updateModeItem(String modeNameStr) {
		if (currModeItem != null) {
			// currModeItem.setWaterLevel(waterLevel);
			status.setTemperature = (byte) currModeItem.getTargetTemperature();
			status.get_rid_cl = (byte) (currModeItem.isNeedCleanlv() ? 0x01
					: 0x00);// 除氯
			status.get_rid_cl_work = (byte) (currModeItem.isNeedBoiled() ? 0x01
					: 0x00);// 保温
			status.setFixedTemperatureTime = (byte) (currModeItem.isNeedWarm() ? 120
					: 0);
			updateUI(status, modeNameStr);
		}
	}

	// 更新温度
	private void updateTemperature(String temperature) {
		Temperature.setText(temperature + "°C");
	}

	boolean hasQuery = false;
	boolean hasClick = false;

	@Override
	protected void onResume() {
		super.onResume();
		if (menu.isMenuShowing()) {
			handler.sendEmptyMessageDelayed(menuclose, 600);

		}
		hasClick = false;

		if (isShowingDialog()) {
			dissLoadingDialog();
		}
		startBlackIceService();
		isDialog = false;
		registerReceiver(receiver, new IntentFilter(PushCallback.IMAction));
		publisher = Thermometer.getInstance(getApplicationContext());

		String str = MSharePerference.getInstance(getApplicationContext()).get(
				MODES);
		List<ModeItem> modeLists;
		if (!str.isEmpty()) {
			modeLists = new Gson().fromJson(str,
					new TypeToken<List<ModeItem>>() {
					}.getType());
		} else {
			modeLists = new ArrayList<ModeItem>();
		}

		updateModeName();
		updateOnOffStatus();
		getOnOffLineStaauts();

		String filePath = Environment.getExternalStorageDirectory()
				+ "/kettle/icon.png";
		try {
			File file = new File(filePath);
			Bitmap bitmap = ImageUtils.getImageFromLocal(filePath);
			userIcon.setImageBitmap(ImageUtils.getRoundedCornerBitmap(bitmap));
		} catch (Exception e) {
			e.printStackTrace();
			Log.d("Image_kettle", "失败 " + e.getMessage());
			DownLoadBmp();
		}
		tv.setText(currUser.getNick_name());
		// if(menu.isMenuShowing()){
		// menu.toggle();
		// }
		titleView.setTitle(currDevice.getName());
		status.setFixedTemperatureTime = modeStatus.setFixedTemperatureTime;

		status.get_rid_cl_work = modeStatus.get_rid_cl_work;
		status.whatmode = (byte) BoliModeUtil
				.getBoliMode(getApplicationContext());
		updateUI(status, MSharePerference.getInstance(getApplicationContext())
				.get(GlobalConfig.MODE));

		handler.sendEmptyMessageDelayed(QUERY, 1000);
		enter_righttoleft = AnimationUtils.loadAnimation(this,
				R.anim.enter_righttoleft);

	}

	/** 获取在线状态 */
	private void getOnOffLineStaauts() {
		// new Thread(new Runnable() {
		//
		// @Override
		// public void run() {
		// String json = HttpUtil.getInstance()
		// .get("121.42.15.85:61680/broker/connections.json?q=protocol_session_id%20LIKE%20"
		// +MSharePerference.getInstance(getApplicationContext()).get(GlobalConfig.MAC));
		// Log.d("mmqtt","json = "+json);
		// try {
		// JSONObject jsonObj = new JSONObject(json);
		// int rows = jsonObj.getInt("total_rows");
		// if(rows >= 1){
		// handler.obtainMessage(ONLINE).sendToTarget();
		// }else{
		// handler.obtainMessage(OFFLINE).sendToTarget();
		// }
		// } catch (JSONException e) {
		// e.printStackTrace();
		// handler.obtainMessage(OFFLINE).sendToTarget();
		// }
		// }
		// }).start();

	}

	/**
	 * 更新当前为煮水状态或者非煮水状态
	 */
	private void updateOnOffStatus() {
		if (status.switchStatus == 0x00) {
			updateTemperature(MSharePerference.getInstance(
					getApplicationContext()).get(GlobalConfig.TargetTemp));
			BoilStatus.setVisibility(View.GONE);
			boilinglayout.setVisibility(View.GONE);
			main_control.setVisibility(View.VISIBLE);
			linear_main_controlline.setVisibility(View.VISIBLE);
			setVisibleWhenBolling(false);
		} else {
			setVisibleWhenBolling(true);
			boilinglayout.setVisibility(View.VISIBLE);
			BoilStatus.setVisibility(View.VISIBLE);
			main_control.setVisibility(View.GONE);
			linear_main_controlline.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		stopBlackIceService();
		unregisterReceiver(receiver);
	}

	/**
	 * 初始化NumberPicker
	 * 
	 * @param height
	 */
	private void initNumberPicker(int height) {
		mNumberPicker = new MNumberPicker(getApplicationContext(), height);
		Display display = getWindowManager().getDefaultDisplay();
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		ViewGroup pickerView = (ViewGroup) inflater.inflate(R.layout.pop_menu,
				null);
		mNumberPicker
				.initNumberPicker(display, getLayoutInflater(), pickerView);
		mNumberPicker.setNumberReceive(this);
	}

	/***/
	TextView water_level, warmup_text;
	TextView dechlorination_text, menu_light_text, menu_sound_text,
			menu_boil_up;;
	private boolean light_status = true, boil_up = true, sound_status = true,
			warm_up = true;

	/**
	 * 右上角
	 */
	private void initCtlMenu() {
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		CtlMenu = (View) inflater.inflate(R.layout.pop_menu, null);

		CtlMenu.findViewById(R.id.dechlorination).setOnClickListener(this);
		// CtlMenu.findViewById(R.id.menu_sound).setOnClickListener(this);
		CtlMenu.findViewById(R.id.menu_boil).setOnClickListener(this);
		CtlMenu.findViewById(R.id.menu_water).setOnClickListener(this);
		CtlMenu.findViewById(R.id.warmup).setOnClickListener(this);

		im1 = (ImageView) CtlMenu.findViewById(R.id.imageView1);
		im2 = (ImageView) CtlMenu.findViewById(R.id.imageView2);
		im3 = (ImageView) CtlMenu.findViewById(R.id.imageView3);

		tv1 = (TextView) CtlMenu.findViewById(R.id.usedmode1);
		tv2 = (TextView) CtlMenu.findViewById(R.id.usedmode2);
		tv3 = (TextView) CtlMenu.findViewById(R.id.usedmode3);

		im1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				needSaveMode = false;
				status.setTemperature = (byte) currenList.get(0)
						.getTargetTemperature();
				updateUI(status, currenList.get(0).getModeTitle());
				updateTemperature(currenList.get(0).getTargetTemperature() + "");
				linear_main_controlline.setVisibility(View.VISIBLE);
				pw.dismiss();
			}
		});

		im2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				needSaveMode = false;
				status.setTemperature = (byte) currenList.get(1)
						.getTargetTemperature();
				updateUI(status, currenList.get(1).getModeTitle());
				updateTemperature(currenList.get(1).getTargetTemperature() + "");
				linear_main_controlline.setVisibility(View.VISIBLE);
				pw.dismiss();
			}
		});

		im3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				needSaveMode = false;
				status.setTemperature = (byte) currenList.get(2)
						.getTargetTemperature();
				updateUI(status, currenList.get(2).getModeTitle());
				updateTemperature(currenList.get(2).getTargetTemperature() + "");
				linear_main_controlline.setVisibility(View.VISIBLE);
				pw.dismiss();
			}
		});

		warmup_text = (TextView) CtlMenu.findViewById(R.id.warmup_text);
		water_level = (TextView) CtlMenu.findViewById(R.id.water_level);
		menu_boil_up = (TextView) CtlMenu.findViewById(R.id.keepwarm);
		dechlorination_text = (TextView) CtlMenu
				.findViewById(R.id.dechlorination_text);
	}

	List<ModeItem> currenList;

	private void updateCurrentData() {
		String json = MSharePerference.getInstance(getApplicationContext())
				.get(GlobalConfig.UsedMode);
		currenList = new Gson().fromJson(json, new TypeToken<List<ModeItem>>() {
		}.getType());
		Log.d("kettle", "更新常用模式" + currenList);
		TextView[] tvs = { tv1, tv2, tv3 };
		ImageView[] imgs = { im1, im2, im3 };
		for (int i = 0; i < 3; i++) {
			tvs[i].setText(currenList.get(i).getModeTitle());
			imgs[i].setImageResource(currenList.get(i).getImage());
		}
	}

	protected void initTitleBar() {
		titleView = (TitleBarView) findViewById(R.id.titleview);
		// titleView.setTitle("我的水壶");
		titleView.setLeftIcon(R.drawable.navicon);
		titleView.setRightIncon(R.drawable.gear);
		titleView.setTitleBarClickListener(new TitleBarHandler() {

			@SuppressLint("NewApi")
			@Override
			public void ClickRight() {
				initPop(appoint_layout.getHeight());
				if (!checkKettle()) {
					return;
				}
				if (!pw.isShowing()
						&& BoilStatus.getVisibility() != View.VISIBLE) {
					pw.setAnimationStyle(R.style.popupAnimation);
					// pw.showAsDropDown(main_control, 0,
					// -getMainControlHeight(),
					// Gravity.BOTTOM);
					linear_main_controlline.setVisibility(View.GONE);
					// pw.showAsDropDown(main_control, 19,
					// (getTotalHeight() - getMainControlHeight()));
					pw.showAtLocation(main_control, Gravity.BOTTOM, 0, 0);

					pw.setOutsideTouchable(true);
				} else {
					linear_main_controlline.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void ClickLeft() {
				menu.toggle();
				isShown = !isShown;
			}
		});
	}

	private int getMainControlHeight() {
		return (/* (android.widget.RelativeLayout.LayoutParams) */main_control
				.getHeight());

	}

	private int getTotalHeight() {
		return rela_total.getLayoutParams().height;
	}

	/**
	 * 初始化点击titlebar右上角按钮弹出pop
	 * 
	 * @param viewHeight
	 */
	private void initPop(int viewHeight) {
		if (initPop)
			return;
		initPop = true;
		pw = new PopupWindow(CtlMenu, LayoutParams.MATCH_PARENT, viewHeight,
				true);
		pw.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss() {
		
				linear_main_controlline.setVisibility(View.VISIBLE);
			}
		});
		pw.setBackgroundDrawable(new BitmapDrawable());
	}

	PopupWindow pop_boil = null;

	/**
	 * 更新主界面ui
	 * 
	 * @param status
	 * @param mode
	 */
	public void updateUI(DeviceStatus status, String mode) {
		MSharePerference.getInstance(getApplicationContext()).update(
				GlobalConfig.MODE, mode);
		updateModeName();
		updateView();
		updateBoilingStatus();
		updateOnOffStatus();

		// Log.d("ServiceDemo", status.setFixedTemperatureTime +
		// "    "+status.get_rid_cl_work);

		// warm_up = (status.setFixedTemperatureTime != 0);
		// boil_up = (status.get_rid_cl_work != 0);
		updatePopView(warmup_text, warm_up,
				getResources().getString(R.string.warm));
		updatePopView(menu_boil_up, boil_up,
				getResources().getString(R.string.cookboil));
	}

	private void initBoil(int viewHeight) {
		if (pop_boil == null) {
			LayoutInflater inflater = (LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View Boiling = (View) inflater.inflate(R.layout.pop_boil, null);

			Button boil_btn = (Button) Boiling.findViewById(R.id.boiling);
			boil_btn.setOnClickListener(this);

			pop_boil = new PopupWindow(Boiling, LayoutParams.MATCH_PARENT,
					viewHeight, true);
			// pop_boil.setBackgroundDrawable(new BitmapDrawable());
		}
	}

	ImageView userIcon;
	TextView tv;

	/**
	 * 初始化侧滑菜单
	 */
	private void initMenu() {
		menu = new SlidingMenu(getApplicationContext());
		menu.setMode(SlidingMenu.LEFT);
		menu.setTouchModeAbove(SlidingMenu.LEFT);
		menu.setFadeDegree(0.35f);
		LayoutInflater layoutInflater = LayoutInflater
				.from(getApplicationContext());
		View slidemenuleftview = layoutInflater.inflate(
				R.layout.slidingmenuview, null);

		userIcon = (ImageView) slidemenuleftview.findViewById(R.id.user_icon);

		tv = (TextView) slidemenuleftview.findViewById(R.id.name);
		tv.setText(currUser.getNick_name());

		(slidemenuleftview.findViewById(R.id.user_icon))
				.setOnClickListener(this);
		(slidemenuleftview.findViewById(R.id.mykettles))
				.setOnClickListener(this);
		(slidemenuleftview.findViewById(R.id.xiguans)).setOnClickListener(this);
		(slidemenuleftview.findViewById(R.id.modes)).setOnClickListener(this);
		(slidemenuleftview.findViewById(R.id.records)).setOnClickListener(this);
		(slidemenuleftview.findViewById(R.id.healthinfos))
				.setOnClickListener(this);
		menu_upgread = (LinearLayout) slidemenuleftview
				.findViewById(R.id.menu_upgrade);

		menu_upgread.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (hasClick) {
					return;
				}
				if (!isShowingDialog()) {
					showLoadingDialog();
				}
				updateApp();

			}
		});

		menu.setMenu(slidemenuleftview);
		menu.setShadowDrawable(R.color.black);
		menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
	}

	/**
	 * 煮水完成后保存自定义煮水模式
	 */
	private void saveNewMode() {
		if (needSaveMode && isStart) {
			needSaveMode = false;
			isStart = false;
			View cus_view = View.inflate(getApplicationContext(),
					R.layout.dialog_update_nickname, null);
			TextView title = (TextView) cus_view.findViewById(R.id.title);
			TextView des = (TextView) cus_view.findViewById(R.id.des);
			final EditText name = (EditText) cus_view
					.findViewById(R.id.nick_name);
			TextView confirm = (TextView) cus_view.findViewById(R.id.confirm);
			name.setHint("模式名称");
			title.setText("是否保存当前模式？");
			des.setText("请输入模式名称：");
			confirm.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					if (!name.getText().toString().trim().isEmpty()) {
						if (name.getText().toString().length() >= 5) {
							UIHandler.obtainMessage(TOASTMSG, "请输入少于5个字的模式名称")
									.sendToTarget();
						} else {
							ModeItem newItem = new ModeItem();
							newItem.setModeTitle(name.getText().toString());
							newItem.setNeedBoiled(boil_up);
							newItem.setNeedCleanlv(cleanCLtime != 0 ? true
									: false);
							newItem.setNeedVoice(false);
							newItem.setNeedWarm(warm_up);
							newItem.setWaterLevel(0);
							newItem.setTargetTemperature(keepWarm_temperature);// status.setTemperature
							String str = MSharePerference.getInstance(
									getApplicationContext()).get(MODES);
							Log.d("qiwei", "保存Item = " + str + "     "
									+ status.setTemperature);
							List<ModeItem> modeLists;
							if (!str.isEmpty()) {
								modeLists = new Gson().fromJson(str,
										new TypeToken<List<ModeItem>>() {
										}.getType());
								modeLists.add(newItem);
							} else {
								modeLists = new ArrayList<ModeItem>();
								modeLists.add(newItem);
							}
							String newModeLists = new Gson().toJson(modeLists);
							MSharePerference.getInstance(
									getApplicationContext()).update(MODES,
									newModeLists);
							updateModeName(name.getText().toString());
							dialog.dismiss();
						}
					} else {
						UIHandler.obtainMessage(TOASTMSG, "请输入新模式名称")
								.sendToTarget();
					}
				}
			});

			showDialog(MainActivityTest.this, cus_view);

		}
		updateCurrentData();
	}

	private void setCustomName() {
		needSaveMode = true;
		modeName.setText("自定义");

	}

	@Override
	public void onClick(final View view) {
		switch (view.getId()) {
		case R.id.button1:
			nextActivity(Modes2Activity.class);
			break;
		case R.id.maintext:
			nextActivity(Modes2Activity.class);
			break;
		case R.id.boilingbtn:

			if (!checkKettle()) {
				return;
			}
			// isStart = false;
			BoilStatus.setVisibility(View.GONE);
			boilinglayout.setVisibility(View.GONE);
			main_control.setVisibility(View.VISIBLE);
			linear_main_controlline.setVisibility(View.VISIBLE);
			if (isStart && needSaveMode) {
				saveNewMode();
			}

			setVisibleWhenBolling(false);
			status.switchStatus = 0;
			status.appointed_timer_on = 0;
			status.appointed_timer_on_aboso_hour = 0;
			status.appointed_timer_on_aboso_min = 0;
			if (TEST_MODE) {
				handler.removeMessages(TEST_AUTO_ADD);
				updateBoilingStatus();
			} else {
				sendCommand();
			}
			break;
		case R.id.menu_upgrade:
			// 更新

			break;
		case R.id.healthinfos:
			nextActivity(HealthInfosActivity.class);
			break;
		case R.id.records:
			nextActivity(RecordActivity.class);
			break;
		case R.id.modes:
			// nextActivity(ModesActivity.class);
			nextActivity(Modes2Activity.class);
			break;
		case R.id.mykettles:
			nextActivity(MyKettles.class);
			break;
		case R.id.xiguans:
			nextActivity(XiGuanActivity.class);
			break;
		case R.id.user_icon:
			nextActivity(UserInfo.class);
			break;
		case R.id.temperature:
			if (BoilStatus.getVisibility() == View.VISIBLE) {
				break;
			}
			isDialog = true;
			baowening = !baowening;
			Temperature.setTextColor(getResources().getColor(R.color.orange));
			temp_unit.setTextColor(getResources().getColor(R.color.orange));

			LayoutInflater inflater3 = getLayoutInflater();
			String title3 = getResources().getString(R.string.warm_temp);
			String unit3 = getResources().getString(R.string.cc);
			/**
			 * 弹出温度
			 */

			AlertUtil.ShowCustomDialog(
					this,
					appoint_layout,
					inflater3,
					title3,
					/* keepWarm_temperature */Integer.parseInt(Temperature
							.getText().toString().trim().replace("°C", "")),
					unit3, 90, 40, 1, new CustomDialogInterface() {

						@Override
						public void onRightClicked() {
							Temperature.setText(keepWarm_temperature + "°C");
							status.setTemperature = (byte) keepWarm_temperature;
							setCustomName();
							MSharePerference.getInstance(
									getApplicationContext()).update(
									GlobalConfig.TargetTemp,
									keepWarm_temperature + "");
							((TextView) view).setText(keepWarm_temperature
									+ "°C");
						}

						@Override
						public void onProgresssChanged(int value) {

							keepWarm_temperature = value;

							// ((TextView) view).setText(keepWarm_temperature
							// + "°C");

						}

						@Override
						public void onLeftClicked() {
							keepWarm_temperature = Integer.parseInt(Temperature
									.getText().toString().trim()
									.replace("°C", ""));
						}

						@Override
						public void dissmiss() {
							isDialog = false;
							Temperature.setTextColor(getResources().getColor(
									R.color.white));
							temp_unit.setTextColor(getResources().getColor(
									R.color.white));
						}
					});

			break;
		case R.id.currmode:
		case R.id.boil_layout:
			if (!checkKettle()) {
				return;
			}
			boilinglayout.setVisibility(View.VISIBLE);
			BoilStatus.setVisibility(View.VISIBLE);
			main_control.setVisibility(View.GONE);
			linear_main_controlline.setVisibility(View.GONE);

			int minutes = DateUtils.diffMinute(ampm, hour, minute);
			System.out.println("minutes = " + minutes);
			status.appointed_timer_on_aboso_hour = (byte) (minutes / 60);
			status.appointed_timer_on_aboso_min = (byte) (minutes % 60);

			status.switchStatus = 1;
			if (boil_up) {
				status.get_rid_cl_work = 1;
			} else {
				status.get_rid_cl_work = 0;
			}
			if (warm_up) {
				status.setFixedTemperatureTime = 120;
			} else {
				status.setFixedTemperatureTime = 0;
			}
			if (cleanCLtime != 0) {
				status.boilingTimer = (byte) cleanCLtime;
				status.get_rid_cl = 1;
			} else {
				status.boilingTimer = 0;
				status.get_rid_cl = 0;
			}
			status.whatmode = (byte) BoliModeUtil
					.getBoliMode(getApplicationContext());
			// status.whatmode = GlobalConfig.WHATMODE;
			status.appointed_timer_on_aboso_hour = 0;
			status.appointed_timer_on_aboso_min = 0;
			// 保存下目标温度

			status.setTemperature = Byte.valueOf(MSharePerference.getInstance(
					getApplicationContext()).get(GlobalConfig.TargetTemp));
			targetTemperature = status.setTemperature;

			Log.d("mmqtt", "before  sendCommand   "
					+ status.setFixedTemperatureTime + "  "
					+ status.get_rid_cl_work);

			status.runNingStatus = 0x01;
			isStart = true;
			if (needSaveMode) {
				modeName.setText("自定义");
			}

			sendCommand();
			saveCurrentMode(false);

			saveWaterLevel(Integer.valueOf(Watertank.getText().toString()
					.replace("ml", "")));
			WaterDateUtil.addData(
					Integer.valueOf(Watertank.getText().toString()
							.replace("ml", "")), getApplicationContext());
			// 开始煮水 新模式名称
			//
			if (TEST_MODE) {
				status.runNingStatus = 1;
				status.switchStatus = 1;
				status.setTemperature = 10;
				handler.sendEmptyMessage(TEST_AUTO_ADD);
				updateBoilingStatus();
			}

			// 更新最近模式

			break;
		case R.id.appoint_layout:
			// 预约
			if (!checkKettle()) {
				return;
			}
			initNumberPicker(appoint_layout.getHeight());
			mNumberPicker.showNumberPicker(MNumberPicker.PICKER_TYPE_TIME12);
			handler.sendEmptyMessageDelayed(DISNUMBER, 60000);
			linear_main_controlline.setVisibility(View.GONE);
			break;

		case R.id.dechlorination:
			// 除氯
			LayoutInflater inflater2 = getLayoutInflater();
			String title2 = getResources().getString(R.string.time);
			String unit2 = getResources().getString(R.string.minute);
			AlertUtil.ShowCustomDialog(this, appoint_layout, inflater2, title2,
					cleanCLtime, unit2, 10, 0, 1, new CustomDialogInterface() {

						@Override
						public void onRightClicked() {
							dechlorination_text.setText(cleanCLtime + "");
							setCustomName();
							if (cleanCLtime != 0) {
								status.boilingTimer = (byte) cleanCLtime;
								status.get_rid_cl = 1;
							} else {
								status.boilingTimer = 0;
								status.get_rid_cl = 0;
							}
							if (cleanCLtime != 0) {
								dechlorination_text.setText(cleanCLtime + "");
							} else {
								dechlorination_text.setText("除氯");
							}
						}

						@Override
						public void onProgresssChanged(int value) {
							cleanCLtime = value;

						}

						@Override
						public void onLeftClicked() {

						}

						@Override
						public void dissmiss() {

						}
					});

			break;
		// case R.id.menu_sound:
		// // 声音
		// if (sound_status) {
		// sound_status = false;
		// } else {
		// sound_status = true;
		// }
		//
		// // sound_status = !sound_status;
		// if (sound_status) {
		// status.beeWarning = 1;
		// } else {
		// status.beeWarning = 0;
		// }
		// updatePopView(menu_sound_text, sound_status, getResources()
		// .getString(R.string.sound));
		// break;
		case R.id.menu_boil:
			// 是否煮沸
			boil_up = !boil_up;
			if (boil_up) {
				status.get_rid_cl_work = 1;
			} else {
				status.get_rid_cl_work = 0;
			}
			setCustomName();
			updatePopView(menu_boil_up, boil_up,
					getResources().getString(R.string.cookboil));
			break;

		case R.id.warmup:
			warm_up = !warm_up;
			if (warm_up) {
				status.setFixedTemperatureTime = 120;
			} else {
				status.setFixedTemperatureTime = 0;
			}
			setCustomName();
			updatePopView(warmup_text, warm_up,
					getResources().getString(R.string.warm));
			break;

		case R.id.menu_water:
			// 水量
			LayoutInflater inflater_water = getLayoutInflater();
			String title_water = getResources().getString(R.string.waterLevel);
			String unit_water = getResources().getString(R.string.millL);
			AlertUtil.ShowCustomDialog(
					this,
					appoint_layout,
					inflater_water,
					title_water,
					Integer.valueOf(Watertank.getText().toString()
							.replace("ml", "")), unit_water, 1500, 0, 10,
					new CustomDialogInterface() {

						@Override
						public void onRightClicked() {
							setCustomName();
							Watertank.setText(nowWaterLevel + "ml");
						}

						@Override
						public void onProgresssChanged(int value) {
							nowWaterLevel = value;

						}

						@Override
						public void onLeftClicked() {
							nowWaterLevel = Integer.valueOf(Watertank.getText()
									.toString().replace("ml", ""));
						}

						@Override
						public void dissmiss() {

						}
					});
			break;
		default:
			break;
		}

	}

	private void saveWaterLevel(int ml) {
		String str = MSharePerference.getInstance(getApplicationContext()).get(
				GlobalConfig.WaterLevel);
		if (!str.startsWith(DateUtils.getTodayDate())) {
			MSharePerference.getInstance(getApplicationContext()).update(
					GlobalConfig.WaterLevel, DateUtils.getTodayDate() + ",");
		}
		str = MSharePerference.getInstance(getApplicationContext()).get(
				GlobalConfig.WaterLevel);
		StringBuilder sb = null;
		if (str.contains(DateUtils.getCurrHour() + "")) {
			String[] list = str.split(",");
			Log.v("Water", str);
			for (int i = 0; i < list.length; i++) {
				Log.v("Water", i + "---------" + list[i]);
			}
			for (int i = 0; i < list.length; i++) {
				if (list[i].contains(DateUtils.getCurrHour() + "")) {
					if (list[i].split(":").length == 2) {
						Log.v("Water", "ml-------->" + ml);
						String value = Integer.valueOf(list[i].split(":")[1])
								+ ml + "";
						list[i] = list[i].split(":")[0] + ":" + value;
					}

				}
			}
			sb = new StringBuilder();
			for (int i = 0; i < list.length; i++) {
				// if (list[i].split(":").length == 2) {
				sb.append(list[i]);
				sb.append(",");
				// }

			}
		} else {
			sb = new StringBuilder();
			sb.append(str);
			sb.append(DateUtils.getCurrHour());
			sb.append(":");
			sb.append(ml);
			sb.append(",");
		}
		MSharePerference.getInstance(getApplicationContext()).update(
				GlobalConfig.WaterLevel, sb.toString());
		Log.d("kettle", "储存最近一天" + sb.toString());
	}

	/**
	 * 保存最近使用模式
	 */
	private void saveCurrentMode(boolean init) {
		if (init) {
			saveCurrentMode(null, true);
			return;
		}
		List<ModeItem> modeLists;
		ModeItem item = new ModeItem();
		item.setModeTitle(modeName.getText().toString());
		item.setCleanlvTime(status.boilingTimer);
		item.setTargetTemperature(status.setTemperature);
		item.setImage(getImageResource(modeName.getText().toString()));
		Log.d("kettle", "保存当前模式" + item);

		String str = MSharePerference.getInstance(getApplicationContext()).get(
				GlobalConfig.UsedMode);

		if (!str.isEmpty()) {
			modeLists = new Gson().fromJson(str,
					new TypeToken<List<ModeItem>>() {
					}.getType());

			for (int i = 0; i < modeLists.size(); i++) {
				if (modeLists.get(i).getModeTitle().equals(item.getModeTitle())) {
					modeLists.remove(i);
					break;
				}
			}

			modeLists.add(0, item);

			for (int i = 0; i < modeLists.size(); i++) {
				if (i >= 3) {
					modeLists.remove(i);
				}
			}
			MSharePerference.getInstance(getApplicationContext()).update(
					GlobalConfig.UsedMode, new Gson().toJson(modeLists));
			Log.d("kettle", "常用模式更新" + modeLists);
		} else {
			saveCurrentMode(true);
		}
		updateCurrentData();
		saveCurrentMode(item, init);
	}

	private void saveCurrentMode(ModeItem item, boolean init) {

		List<ModeItem> modeLists = null;

		String str = MSharePerference.getInstance(getApplicationContext()).get(
				GlobalConfig.UsedMode);

		if (!str.isEmpty()) {
			modeLists = new Gson().fromJson(str,
					new TypeToken<List<ModeItem>>() {
					}.getType());
		}
		if (init && str.isEmpty()) {
			modeLists = new ArrayList<ModeItem>();
			ModeItem default_item0 = new ModeItem();
			default_item0.setModeTitle("婴儿奶粉");
			default_item0.setCleanlvTime(10);
			default_item0.setTargetTemperature(80);
			default_item0.setImage(R.drawable.baby_milk);

			ModeItem default_item1 = new ModeItem();
			default_item1.setModeTitle("咖啡");
			default_item1.setCleanlvTime(10);
			default_item1.setTargetTemperature(95);
			default_item1.setImage(R.drawable.coffeetea);

			ModeItem default_item2 = new ModeItem();
			default_item2.setModeTitle("绿茶");
			default_item2.setCleanlvTime(10);
			default_item2.setTargetTemperature(70);
			default_item2.setImage(R.drawable.blacktea);

			modeLists.add(0, default_item0);
			modeLists.add(1, default_item1);
			modeLists.add(2, default_item2);

			String newModeLists = new Gson().toJson(modeLists);
			MSharePerference.getInstance(getApplicationContext()).update(
					GlobalConfig.UsedMode, newModeLists);
			Log.d("kettle", "初始化模式" + newModeLists);
			return;
		}
	}

	/**
	 * 根据模式名字获取图片
	 * 
	 * @param string
	 * @return
	 */
	private int getImageResource(String string) {
		int[] nameList = new int[] { R.array.milk_type, R.array.redtea_type,
				R.array.whitetea_type, R.array.yellowtea_type,
				R.array.blacktea_type, R.array.puer_type, R.array.coffee_type,
				R.array.greentea_type, R.array.wulongtea_type,
				R.array.flowertea_type, R.array.flowerglasstea_type,
				R.array.soap_type };

		int[] imageList = new int[] { R.drawable.milk, R.drawable.redtea,
				R.drawable.whitetea, R.drawable.yellowtea, R.drawable.blacktea,
				R.drawable.puertea, R.drawable.coffeetea, R.drawable.greentea,
				R.drawable.wulongtea, R.drawable.flowertea,
				R.drawable.flowerglasstea, R.drawable.soap };

		for (int i = 0; i < nameList.length; i++) {
			String[] list = getResources().getStringArray(nameList[i]);
			for (int j = 0; j < list.length; j++) {
				if (string.equals(list[j])) {
					return imageList[i];
				}
			}
		}
		return R.drawable.custom;
	}

	/**
	 * 水壶快检
	 * 
	 * @return
	 */
	private boolean checkKettle() {
		if (status.test1 != 0) {
			showTextToast(getResources().getString(R.string.toastmessage));
			return false;
		} else {
			return true;
		}
	}

	private byte[] queryResult = new byte[] { (byte) 0xE0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0 };

	/**
	 * 发送请求
	 */
	private void sendQueryCommand() {
		if (!TEST_MODE) {
			if (!getTopic().isEmpty()) {
				// if (publisher == null) {
				// Log.v("null", "-------->" + "is null");
				// publisher = Thermometer
				// .getInstance(getApplicationContext());
				// }
				publisher.sendControlText(queryResult);
				String request = ByteUtils.printHexString(queryResult);
				Log.d("mmqtt", "request = " + request);

				if (!isShowingDialog()) {
					Log.v("dialog", " i am int he dialog showing");
					showLoadingDialog();
				} else {
					Log.v("dialog", " i am inthe dialog   dounot showing");
				}
			}
		}
	}

	/**
	 * 更新popwindow内容 ，保温pop和煮沸pop
	 * 
	 * @param view
	 * @param status
	 * @param text
	 */
	private void updatePopView(TextView view, boolean status, String text) {
		String on = getResources().getString(R.string.on);
		String off = getResources().getString(R.string.off);
		Drawable onDrawable = getResources().getDrawable(
				R.drawable.shape_ring_pink);
		Drawable offDrawable = getResources().getDrawable(
				R.drawable.shape_ring_grey);
		int onColor = getResources().getColor(R.color.pink);
		int offColor = getResources().getColor(R.color.grey);
		if (status) {
			view.setText(text);
			view.setBackground(onDrawable);
			view.setTextColor(onColor);
		} else {
			view.setText(text);
			view.setBackground(offDrawable);
			view.setTextColor(offColor);
		}
	}

	/**
	 * 广播接受者，接收水壶主动广播内容
	 */
	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				ChannelObject obj = (ChannelObject) intent
						.getSerializableExtra("data");
				if (obj.getDataType() == ChannelObject.SEND) {
					Log.d("mmqtt",
							"水壶返回 ---> "
									+ ByteUtils.printHexString(obj.getData()));
					byte[] result = (byte[]) obj.getData();
					zeroByte = result[0];

					DeviceStatus status0 = FactoryDataBody
							.createFactoryDataBody(FactoryDataBody.RESPONSE,
									null).toObject(result);
					dissLoadingDialog();
					if (status0 != null && result[0] == -112) {
						status = status0;

						handler.sendEmptyMessage(UPDATE_VIEW);
						Log.d("mmqtt", "status = " + status0.toString());
					} else if (status0 != null && result[0] == -111) {
						// 水壶按键/状态返回
						// if(status0.switchStatus == 0){
						// return;
						// }
						status = status0;
						Log.d("mqttdetails",
								"水壶返回 status = " + status.toString());
						handler.sendEmptyMessage(UPDATE_BOILING_VIEW);
					} else {
						Log.d("mmqtt", "result[0] = " + result[0]);
					}

					checkKettle();

				} else {
					if (obj.getDataType() == ChannelObject.LOST_CONNECT) {
						showTextToast("水壶掉线了");
					} else {
						Log.d("mmqtt",
								"自己返回 ---> "
										+ ByteUtils.printHexString(obj
												.getData()));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	public boolean checkCanDiss(int type, Object... objs) {
		// isStart = false;
		linear_main_controlline.setVisibility(View.VISIBLE);
		return true;
	}

	@Override
	public void updateDate(int year, int month, int day) {
	}

	@Override
	public void updateTime(int hour, int minte) {

	}

	@Override
	public void updateTime12(int ampm, int hour, int minte) {
		Log.d("mmqttfuck", "ampm = " + ampm + "  hour = " + hour
				+ "   minute = " + minte + "   当前小时 = "
				+ Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
		// linear_main_controlline.setVisibility(View.VISIBLE);
		this.ampm = ampm;
		this.hour = hour;
		this.minute = minte;
		status.appointed_timer_on = 1;

		status.appointed_timer_on_aboso_hour = (byte) (hour - Calendar
				.getInstance().get(Calendar.HOUR_OF_DAY));
		if (status.appointed_timer_on_aboso_hour < 0) {
			status.appointed_timer_on_aboso_hour += 24;
		}
		// if(hour == Calendar.getInstance().get(Calendar.HOUR_OF_DAY)){
		// status.appointed_timer_on_aboso_min = (byte) minte;
		// }else{
		status.appointed_timer_on_aboso_min = (byte) (minte - Calendar
				.getInstance().get(Calendar.MINUTE));
		// }
		if (status.appointed_timer_on_aboso_min < 0) {
			status.appointed_timer_on_aboso_min += 60;
		}

		if (status.appointed_timer_on_aboso_hour < 0) {
			status.appointed_timer_on_aboso_hour = 0;
		}
		if (status.appointed_timer_on_aboso_min < 0) {
			status.appointed_timer_on_aboso_min = 0;
		}
		status.runNingStatus = 1;
		status.switchStatus = 1;
		status.whatmode = (byte) BoliModeUtil
				.getBoliMode(getApplicationContext());
		Log.d("mmqttfuck", "预约 时 = " + status.appointed_timer_on_aboso_hour
				+ "  预约分 = " + status.appointed_timer_on_aboso_min);
		status.setTemperature = Byte.valueOf(MSharePerference.getInstance(
				getApplicationContext()).get(GlobalConfig.TargetTemp));
		if (boil_up) {
			status.get_rid_cl_work = 1;
		} else {
			status.get_rid_cl_work = 0;
		}
		if (warm_up) {
			status.setFixedTemperatureTime = 120;
		} else {
			status.setFixedTemperatureTime = 0;
		}
		if (cleanCLtime != 0) {
			status.boilingTimer = (byte) cleanCLtime;
			status.get_rid_cl = 1;
		} else {
			status.boilingTimer = 0;
			status.get_rid_cl = 0;
		}
		sendCommand();
		if (TEST_MODE) {
			status.switchStatus = 1;
			updateBoilingStatus();
		}
		UIHandler.obtainMessage(
				TOASTMSG,
				"距离开始时间为 " + status.appointed_timer_on_aboso_hour + "小时"
						+ status.appointed_timer_on_aboso_min + "分钟")
				.sendToTarget();
		// isStart = true;
		// setCustomName();
	}

	int ampm, hour, minute;

	@Override
	public void leftBtnClick() {
		status.appointed_timer_on = 0;
		status.appointed_timer_on_aboso_hour = 0;
		status.appointed_timer_on_aboso_min = 0;
		status.runNingStatus = 0;
		linear_main_controlline.setVisibility(View.VISIBLE);
		sendCommand();
	}

	private void setAddInvisable(boolean flag) {
		// TODO Auto-generated method stub
		if (flag) {
			button1.setVisibility(View.GONE);
		} else {
			button1.setVisibility(View.VISIBLE);
		}

	}

	/**
	 * 不可见true
	 * 
	 * @param flag
	 */
	private void setVisibleWhenBolling(boolean flag) {
		setAddInvisable(flag);
		titleView.setRightIconInVisiable(flag);
	}

	private long lastTime = 0;// 提供一个变量来记录上一次按下的时间

	private void exit() {
		// 得到当前的系统时间（毫秒）
		long time = System.currentTimeMillis();
		if (time - lastTime > 2000) { // 如果两次时间太过长，大于2秒，那就不要退出，提示需要再按一次
			showTextToast(getResources().getString(R.string.main_confirm_exit));

		} else {// 如果两按下的时间是两秒内，则退出
			com.quzi.kettle.activitise.added.ActivityManager.getInstance()
					.exit();
			// 如果用户是第一次按，则将当前的时间保存为上一次按的时间，这样用户再按一下就可以退出了

		}
		lastTime = time;
	}

	/**
	 * 点击返回按键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {// 如果按下的是回退健
			// 表示按下回退键且不是常按
			if (event.getAction() == KeyEvent.ACTION_DOWN
					&& event.getRepeatCount() == 0) {
				exit();
				// 调用上面写的退出

				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 下载bitmap图片
	 */
	private void DownLoadBmp() {
		Map<String, String> request = new HashMap<String, String>();
		request.put("uuid", MyApplication.UUID);
		AsyncHttpUtilClient.request(
				getApplicationContext(),
				new AsyncBean(AsyncHttpUtilClient.GET,
						MyApplication.url
								+ MyApplication.requestMap
										.get(MyApplication.USER_ICON),
						MyApplication.header, new RequestParams(request)),
				new IconResponse<IconString>() {

					@Override
					public void onSuccess(IconString t) {

						byte[] icon = Base64.decode(t.getIcon(), 0);

						String filePath = Environment
								.getExternalStorageDirectory()
								+ "/kettle/icon.png";
						Log.d("Image_kettle", "获取图片成功");
						try {
							File file = new File(filePath);
							file.delete();
						} catch (Exception e) {
							e.printStackTrace();
						}
						Log.d("quzi", "filePath  +" + filePath);
						if (!new File(filePath).getParentFile().exists()) {
							new File(filePath).getParentFile().mkdirs();
						}
						try {
							ImageUtils.saveImage(filePath, icon);
						} catch (IOException e) {
							e.printStackTrace();
						}
						File file = new File(filePath);
						Bitmap bitmap = ImageUtils.getImageFromLocal(filePath);
						userIcon.setImageBitmap(ImageUtils
								.getRoundedCornerBitmap(bitmap));
					}

					@Override
					public void onFailure(int arg0, String arg1) {

					}
				});
	}

	/**
	 * 侧滑菜单检测app版本更新
	 */
	private void updateApp() {
		Map<String, String> request = new HashMap<String, String>();
		AsyncHttpUtilClient.doGet(AsyncHttpUtilClient.GET, MyApplication.url
				+ MyApplication.requestMap.get(MyApplication.UPDATE_INFO),
				null, new RequestParams(request),
				new UpdateInfoResponse<String>() {

					@Override
					public void onSuccess(String result) {
						dissLoadingDialog();
						Log.e("updateinfo", result);
						if (result.isEmpty()) {
							showTextToast("您的app是最新版本");
						}
						String[] res = result.split("-");
						String str = res[1];
						str = str.replace("v", "");
						String version = "1.0";
						int versionCode = 0;

						try {
							PackageManager manager = MainActivityTest.this
									.getPackageManager();
							PackageInfo info = manager.getPackageInfo(
									MainActivityTest.this.getPackageName(), 0);
							version = info.versionName;
							versionCode = info.versionCode;
						} catch (Exception e) {
							e.printStackTrace();
						}
						try {
							double newVersion = Double.valueOf(str);
							double nowVersion = Double.valueOf(version.replace(
									"v", ""));
							if (newVersion > nowVersion) {
								if (hasClick) {
									return;
								}
								hasClick = true;
								Intent intent = new Intent();
								intent.setAction("android.intent.action.VIEW");
								Uri content_url = Uri
										.parse("http://112.74.15.198/" + result);
								intent.setData(content_url);
								startActivity(intent);
							} else {
								showTextToast("您的app是最新版本");
							}
						} catch (Exception e) {
							e.printStackTrace();
							showTextToast("您的app是最新版本");
						}
						Log.d("updateinfo", version + "    " + versionCode
								+ "     " + str);
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						super.onFailure(arg0, arg1);
					}
				});
	}

}
